// 百度翻译：已废弃

// 多语言一键翻译，只进行增量替换
// 新增翻译文件时，翻译源文件要改动一点才能自动生成译文
const md5 = require('md5');
const path = require('path');
const fs = require('fs');
// const lanDir = path.resolve(__dirname, "./lan"); //翻译凭据目录
const lanDir = path.resolve(__dirname, "../src/lang/lan"); //翻译凭据目录
const baseLan = process.argv[2];



if (!baseLan) {
    return console.log("缺少翻译凭据");
}
let lanList = fs.readdirSync(lanDir).map(file => path.basename(file, ".json")).filter(lan => lan != baseLan);

let count = lanList.length;
console.log(lanList);
// 只处理一层对象
function getModifyPart(obj1, obj2) {
    const modifyObj = {};
    const modifyTextArr = [];
    for (const [key, value] of Object.entries(obj1)) {
        if (obj2[key]) {
            for (const [key1, value1] of Object.entries(value)) {
                if (obj1[key][key1] != obj2[key][key1]) {
                    !modifyObj[key] && (modifyObj[key] = {});
                    modifyObj[key][key1] = value1;
                    modifyTextArr.push(value1)
                }
            }
        } else {
            modifyObj[key] = value;
            modifyTextArr.push(...Object.values(value))
        }
    }
    return { modifyObj, modifyText: modifyTextArr.join("⚠") };
}

function transErrTip(error, lan) {
    const tips = {
        "52001": "请求超时：请重试",
        "52002": "系统错误：请重试",
        "54003": "访问频率受限：请降低您的调用频率，或进行身份认证后切换为高级版/尊享版",
        "54004": "账户余额不足：请前往百度翻译管理控制台为账户充值",
        "54005": "长query请求频繁：请降低长query的发送频率，3s后再试",
        "58001": "译文语言不支持：若在支持的语言范围内，请升级为企业尊享版后重试 https://fanyi-api.baidu.com/product/113",
        "58002": "服务当前已关闭：请前往百度翻译管理控制台开启服务"
    }
    console.error(`[${lan}]-----------`, tips[error.error_code] || error.error_msg)
}

function deepMerge(target, ...sources) {
    if (!sources.length) return target;
    const source = sources.shift();

    if (isObject(target) && isObject(source)) {
        for (const key in source) {
            if (isObject(source[key])) {
                if (!target[key]) Object.assign(target, { [key]: {} });
                deepMerge(target[key], source[key]);
            } else {
                Object.assign(target, { [key]: source[key] });
            }
        }
    }

    return deepMerge(target, ...sources);
}

function isObject(item) {
    return (item && typeof item === 'object' && !Array.isArray(item));
}

const baseFile = fs.readFileSync(path.resolve(__dirname, lanDir, `${baseLan}.json`)); // 翻译凭据文件
const comparePath = path.resolve(`${path.resolve("script/.lan")}/${baseLan}.json`);

let compareFile; //对比文件
if (fs.existsSync(comparePath)) {
    compareFile = fs.readFileSync(comparePath);
} else {
    fs.mkdirSync(path.resolve(`script/.lan`), { recursive: true });
    fs.writeFileSync(comparePath, "{}");

    // fs.chmod(comparePath, 0o444, (err) => { });
    compareFile = "{}"
}

const { modifyObj, modifyText } = getModifyPart(JSON.parse(baseFile), JSON.parse(compareFile));
let allText = [];
Object.values(JSON.parse(baseFile)).forEach(obj => Object.values(obj).forEach(text => allText.push(text)))
allText = allText.join("⚠");

console.log("待修改对象：", modifyObj);
if (JSON.stringify(modifyObj) === "{}") {

    return console.log("源文件无改动")
}

lanList.forEach(lan => {
    const transPath = path.resolve(lanDir, `${lan}.json`);
    const hasText = fs.readFileSync(transPath).length;

    const signQuery = {
        appid: "20230911001812703",
        from: baseLan,
        to: lan,
        q: hasText ? modifyText : allText,
        salt: Date.now(),
        secret: "wI7xd8eLmRDbvKngTeXH"
    }
    const sign = md5(signQuery.appid + signQuery.q + signQuery.salt + signQuery.secret)
    const requestUrl = `https://fanyi-api.baidu.com/api/trans/vip/translate?q=${encodeURIComponent(signQuery.q)}&from=${signQuery.from}&to=${signQuery.to}&appid=${signQuery.appid}&salt=${signQuery.salt}&sign=${sign}`;
    fetch(requestUrl).then(res => {
        return res.json()
    }).then(data => {
        if (data.error_code) {
            return transErrTip(data, lan)
        }
        if (hasText) {

            data.trans_result.forEach(item => {
                const translateTextArr = item.dst.toString().replaceAll("｛", "{").replaceAll("｝", "}").split("⚠");

                for (const [key, value] of Object.entries(modifyObj)) {
                    for (const [key1, value1] of Object.entries(value)) {
                        modifyObj[key][key1] = translateTextArr.shift()
                    }
                }

            })
            // const transPath = path.resolve(__dirname, `lan/${lan}.json`);
            const transFile = fs.readFileSync(transPath)
            const transObj = JSON.parse(transFile.length ? transFile : "{}");
            // Object.assign(transObj, modifyObj)
            const mergeObj = deepMerge({}, transObj, modifyObj)

            fs.writeFileSync(transPath, JSON.stringify(mergeObj, null, 4))
        } else {
            let transArr = [];
            data.trans_result.forEach(item => {
                transArr.push(...item.dst.toString().replaceAll("｛", "{").replaceAll("｝", "}").split("⚠"))
            })
            let _obj = JSON.parse(baseFile);
            Object.keys(_obj).forEach(key => Object.keys(_obj[key]).forEach(key1 => _obj[key][key1] = transArr.pop()))
            fs.writeFileSync(transPath, JSON.stringify(_obj, null, 4))
        }


        fs.copyFileSync(transPath, path.resolve(`script/.lan/${lan}.json`))
        console.log(`${lan}翻译完毕：${transPath}`);

    }).catch(err => {
        console.log(err);
    }).finally(() => {
        count--;
        count == 0 && fs.copyFileSync(path.resolve(lanDir, `${baseLan}.json`), comparePath)
    })
})

